<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名：admin / user">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码：123456" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn flex justify-between">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> 登录 </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { type ElForm, ElNotification } from 'element-plus'
import { CircleClose, UserFilled, User, Lock } from '@element-plus/icons-vue'

import { getTimeState } from '@/utils'
import { HOME_URL } from '@/config/route'
import { useUserStore } from '@/store/modules/user'

const router = useRouter()
const userStore = useUserStore()

type FormInstance = InstanceType<typeof ElForm>
const loginFormRef = ref<FormInstance>()
const loginRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const loading = ref(false)
const loginForm = reactive<LoginFormModule>({
  username: '',
  password: ''
})

/**
 * 登录
 * @param formEl 表单实例
 */
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      // 1.执行登录接口
      await userStore.login({ ...loginForm })
      // 2.跳转到首页
      router.push(HOME_URL)
      ElNotification({
        title: getTimeState(),
        message: '欢迎登录 YiKang-Admin',
        type: 'success',
        duration: 3000
      })
    } finally {
      loading.value = false
    }
  })
}

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    const eKey = (window.event as KeyboardEvent) || e
    if (eKey.code === 'Enter' || eKey.code === 'enter' || eKey.code === 'NumpadEnter') {
      if (loading.value) return
      login(loginFormRef.value)
    }
  }
})
</script>

<style scoped lang="scss">
:deep(.el-form) {
  .el-form-item {
    margin-bottom: 40px;
  }
}

.login-btn {
  width: 100%;
  margin-top: 40px;
  white-space: nowrap;

  .el-button {
    width: 185px;
  }
}
</style>
